﻿KISSY.add("fgt/citysuggestion", function (S, Suggest) {

    var SUGGEST_MOST_COUNT = 10;

    function CitySuggestion(textInput, store, config) {
        var self = this;

        self._init(textInput, store, config || {});
    }

    S.augment(CitySuggestion, {
        _init: function (textInput, store, config) {
            var self = this;

            self.config = S.merge(
                {
                    callbackFn: "suggestCallback",
                    submitOnSelect: false,
                    containerWidth: "215px"
                }, config);

            self.textInput = S.all(textInput);
            self.store = S.all(store);
            self.suggest = new Suggest(textInput, CONFIG["cityInfo"], self.config);

            self._bindEvent();

        },

        _bindEvent: function () {
            var self = this,
                All = S.all,
                suggestStore = self.store,
                suggest = self.suggest,
                textInput = self.textInput,
                onItemSelectFn = self.config.onItemSelectFn;

            function _keywordFilter(array, term) {
                var term = term.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"),
                    matcher = new RegExp(term, "i");
                return S.filter(array, function (item) {
                    return matcher.test(item[0]) || matcher.test(item[1]);
                });
            }

            suggest.on("dataReturn", function (event) {
                var self = this,
                    data = self.dataSource || [],
                    dataItem,
                    term = this.query || "",
                    result = [],
                    count = 0;

                for (var i = 0, len = data.length; i < len; ++i) {
                    dataItem = data[i];
                    result.push([dataItem["cName"], dataItem["eName"] + "(" + dataItem["sName"] + ")", dataItem["id"]]);
                }

                result = _keywordFilter(result, term);
                result = S.filter(result, function (item, index) {
                    return index < SUGGEST_MOST_COUNT;
                });
                self.returnedData = result;
            });

            suggest.on("itemSelect", function (event) {
                var self = this,
                    selectedItem = self.selectedItem;

                if (selectedItem) {
                    var kid = All(selectedItem).attr("kid");
                    if (kid) {
                        suggestStore.val(kid);
                    }
                    if (typeof onItemSelectFn == "function") {
                        onItemSelectFn(selectedItem);
                    }
                }
            });

            textInput.on("blur", function (event) {
                var self = All(this),
                    term = self.val(),
                    returedData = suggest.returnedData;

                if (term !== "") {
                    if (returedData) {
                        var isPresiceMatch = false,
                        index;
                        for (var i = 0, len = returedData.length; i < len; ++i) {
                            if (returedData[i][0] === term) {
                                isPresiceMatch = true;
                                index = i;
                                break;
                            }
                        }
                        if (isPresiceMatch) {
                            suggestStore.val(returedData[index][2]);
                        }
                        else
                            if (returedData.length > 0) {
                                self.val(returedData[0][0]);
                                suggestStore.val(returedData[0][2]);
                            }
                            else {
                                self.val("");
                            }
                    }
                }
                else {
                    self.val("");
                }
            });
        },

        setCity: function (cityId) {
            var self = this,
                data = CONFIG["cityInfo"] || [],
                suggestStore = self.store,
                textInput = self.textInput,
                dataItem;

            suggestStore.val(cityId);
            for (var i = 0, len = data.length; i < len; ++i) {
                dataItem = data[i];
                if (dataItem["id"] == cityId) {
                    textInput.val(dataItem["cName"]);
                }
            }
        }
    });

    S.FGT.CitySuggestion = CitySuggestion;
    return CitySuggestion;

}, {
    requires: ["suggest"]
});